/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.webuser.rest;

import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.annotation.Log;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.utils.StringUtils;
import me.zhengjie.webuser.domain.WebUsers;
import me.zhengjie.webuser.service.WebUsersService;
import me.zhengjie.webuser.domain.vo.WebUsersQueryCriteria;
import lombok.RequiredArgsConstructor;
import java.util.List;

import org.apache.ibatis.jdbc.Null;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import me.zhengjie.utils.PageResult;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

/**
* @author meorin
* @date 2024-12-07
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "webuser管理")
@RequestMapping("/api/webUsers")
public class WebUsersController {

    private final WebUsersService webUsersService;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('webUsers:list')")
    public void exportWebUsers(HttpServletResponse response, WebUsersQueryCriteria criteria) throws IOException {
        webUsersService.download(webUsersService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询webuser")
    @ApiOperation("查询webuser")
    @PreAuthorize("@el.check('webUsers:list')")
    public ResponseEntity<PageResult<WebUsers>> queryWebUsers(WebUsersQueryCriteria criteria, Page<Object> page){
        return new ResponseEntity<>(webUsersService.queryAll(criteria,page),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增webuser")
    @ApiOperation("新增webuser")
    @PreAuthorize("@el.check('webUsers:add')")
    public ResponseEntity<Object> createWebUsers(@Validated @RequestBody WebUsers resources){
        webUsersService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改webuser")
    @ApiOperation("修改webuser")
    @PreAuthorize("@el.check('webUsers:edit')")
    public ResponseEntity<Object> updateWebUsers(@Validated @RequestBody WebUsers resources){
        webUsersService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除webuser")
    @ApiOperation("删除webuser")
    @PreAuthorize("@el.check('webUsers:del')")
    public ResponseEntity<Object> deleteWebUsers(@RequestBody List<Integer> ids) {
        webUsersService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @PostMapping("/info")
    @Log("更新个人信息")
    @ApiOperation("更新个人信息")
    @AnonymousAccess
    public ResponseEntity<Object> updateInfo(@RequestBody WebUsers resources) {
//        // 获取当前登录用户ID
//        Long currentUserId = SecurityUtils.getCurrentUserId();
//
//        // 校验请求中的用户ID是否匹配当前用户
//        if (!currentUserId.equals(resources.getId())) {
//            throw new AccessDeniedException("无权修改他人信息");
//        }

        webUsersService.updateInfo(resources);
        return ResponseEntity.ok().build();
    }

    /**
     * 用户头像上传接口
     * @param file 上传的图片文件
     * @return 标准化响应体
     */
    @PostMapping("/avatar")
    @Log("上传修改webUsers头像")
    @ApiOperation("上传修改webUsers头像")
    @AnonymousAccess
    public ResponseEntity<Object> updateWebUsersAvatar(
            @RequestParam("file") MultipartFile file,
            @Validated @ModelAttribute WebUsers resources
    ){
        webUsersService.updateAvatar(file,resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @GetMapping(value = "/avatar")
    @Log("获取webUsers头像")
    @ApiOperation("获取webUsers头像")
    @AnonymousAccess
    public ResponseEntity<Resource> getWebUsersAvatar(
            @RequestParam(value = "username", required = false) String username,
            @RequestParam(value = "id", required = false) Integer id,
            WebRequest webRequest // 添加 WebRequest 参数
    ) {
        // 校验逻辑
        if (id == null && StringUtils.isEmpty(username)) {
            throw new BadRequestException("ID或用户名至少需要提供一项");
        }

        WebUsersQueryCriteria criteria = new WebUsersQueryCriteria();
        if (id != null) criteria.setId(id);
        if (username != null) criteria.setUsername(username);

        // 传递 webRequest 到 Service
        return webUsersService.getAvatar(criteria, webRequest);
    }

}